import requests
import csv


def city_name():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init'
    }
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9153'
    city_code = requests.get(url, headers=headers, verify=True)
    city_code_list = city_code.text.split("|")
    city_dict = {}
    for k, i in enumerate(city_code_list):
        if '@' in i:
            city_dict[city_code_list[k + 1]] = city_code_list[k + 2].replace(' ', '')

    csvFile = open('c://Users//Administrator//Desktop//test.csv', 'a', newline='', encoding='utf-8')
    writer = csv.writer(csvFile)
    for i, k in enumerate(city_dict):
        writer.writerow([k, city_dict[k]])
    csvFile.close()
    return 'success'


def main():
    city_name()


if __name__ == '__main__':
    main()
